var pageNo = 1;     //当前页
var pageSize = 10;   //每页记录数
var pageList;
var dataJson;
var windowWidth = $(window.body).width();    // 计算机屏幕宽度
var windowHeight = $(window.body).height();  // 计算机屏幕高度
var titleList = ["全部学院","全部专业","全部班级","全部年级"];

jQuery(function ($) {
    /*--------------------------------------------------------------------*/
    $(".dropdown-toggle").dropdown();
    $('.s1').click(function () {//查询事件
        showMyModel('list',1);
    });
    $('.s2').click(function () {//查询事件
        showMyModel('list',2);
    });
    //设置全选事件
//    $('#selectAll').click(function () {
//		$('input[name=pid]').prop("checked",$(this).prop('checked'));//全选
//    });
    
   
    $(".form-control").keydown(function(event){
        if(event.keyCode==13){
            showMyModel('list',2);
            return false;
        }
    });
    
    //确认导入
    $('#fileBtn').click(function () {
        $("#uploadimg-form").validate({
            rules: {
                "fileUpload": {
                    required: true,
                    accept: "xls|xlsx"
                }
            },
            messages: {
                "fileUpload": {
                    required: "",
                    accept: "文件格式不支持，请上传  xls|xlsx 文件"
                }
            },
            submitHandler: function() {
                $("#uploadimg-form").ajaxSubmit({
                    url:"/huaqiao/parent/upload",
                    type:"post",
                    enctype:"multipart/form-data",
                    contentType: "application/json;charset=utf-8",
                    dataType:"json",
                    async:true,
                    cache:false,
                    beforeSend:function(xhr){
                    	
                    },
                    error: function(error) {
                    	alert("数据导入失败！");
                    },
                    success: function(data){
                    	alert(data);
                    },
                    complete:function(){
                        $("#fileUpload").val("");
                        importHide();
                        pageNo=1;
                        showMyModel('list',0);
                    }
                });
                return false;
            }
        });
    });
    pageList = $('.pagination').find('a');
    setPageClick();
    setOrg();
    resetOrg();
    showMyModel('list',0);
});



/*-------------------------------设置分页事件开始-------------------------------------*/
function setPageClick(){
	pageList.each(function (index,element) {//分页点击事件
        $(element).click(function () {
        	pageNo = $(this).text(); 
        	if(pageNo>Pagination.pageNo&&Pagination.pageNo==Pagination.pageCount){
        		return alert("当前是最后一页");
        	}else if(pageNo>Pagination.pageCount){
            	pageNo=Pagination.pageCount;
            }else if(pageNo==Pagination.pageNo){
                return;
            }
            showMyModel('list',2);
        });
    });
	$(".pagination span").each(function (i) {
        if (i == 1) {//上一页按钮
            this.onclick = function () {
            	pageNo=Pagination.pageNo-1;
            	if(pageNo>Pagination.pageCount||pageNo<1||pageNo==Pagination.pageNo){
            		return alert("当前是第一页");
                }
            	showMyModel('list',0);
            };
        } else if (i == 2) {//下一页按钮
            this.onclick = function () {
            	pageNo=Pagination.pageNo+1;
            	if(pageNo>Pagination.pageCount||pageNo<1||pageNo==Pagination.pageNo){
            		return alert("当前是最后一页");
                }
            	showMyModel('list',0);
            };
        } else if (i == 0) {
            this.onclick = function () {
            	pageNo=1;
            	Pagination.pageNo==1?alert("当前是第一页"):showMyModel('list',0);
            };
        } else if (i == 3) {
            this.onclick = function () {
            	pageNo=Pagination.pageCount;
            	Pagination.pageNo==Pagination.pageCount?alert("当前是最后一页"):showMyModel('list',0);
            };
        }
    });
}
/*-------------------------------设置分页事件结束-------------------------------------*/


/*-------------------------------模态框-------------------------------------*/
function showMyModel(type,pid) {
    $("<div id='bg'></div>").width(windowWidth * 1).height(windowHeight * 1).click(function() {}).appendTo("body").fadeIn(200);
    switch(type){
        case 'list'://查询多条家长信息
            setParameterOfList(pid);
            getDataOfList();
            break;
        case 'delete'://删除家长信息
            $('#delete_alert').css({zIndex:99999});
            setParameterOfDelete();
            break;
        case 'query'://查看家长信息
            hideMyModel();
            setParameterOfQuery(pid);
            getDataOfQuery();
            showModel();
            break;
        case 'add'://添加家长信息
            hideMyModel();
            setParameterOfAdd();
            showModel();
            break;
        case 'modify'://修改家长信息
            hideMyModel();
            setParameterOfModify(pid);
            getDataOfQuery();
            showModel();
            break;
        case 'pwd'://修改家长密码
            hideMyModel();
            setParameterOfpwd(pid);
            getDataOfQuery();
            showModelPwd();
            break;
        case 'editOK':
            hideMyModel();
            getParentInfo();
            break;
        case 'editOK1':
            hideMyModel();
            getParentInfoPwd();
            break;
        case 'import'://导入家长信息
            $('.alert_custom_common').css({zIndex:99999});
            importList();
            break;
        case 'cancel':
            hideAlert();
            hideMyModel();
            hideMyModel();
            break;
        default:;
    }
}
function hideMyModel() {
    $("#bg").remove();
    $("#selectAll").prop('checked',false);
}
/*-------------------------------设置参数-------------------------------------*/
function setParameterOfList(searchType) {
    var $instituteName = ''; //学院名称
    var $majorName = '';     //专业
    var $gradeName = '';	 //年级
    var $className = '';	 //班级
    var $info = '';          //班级信息（模糊查询）
    if((searchType&1)==1){
        $instituteName=$("#ins button").text().replace(/(\\n|\\t|\s|全部学院)/g,'');
        $majorName=$("#major button").text().replace(/(\\n|\\t|\s|全部专业)/g,'');
        $gradeName=$("#grade button").text().replace(/(\\n|\\t|\s|全部年级)/g,'');
        $className=$("#class button").text().replace(/(\\n|\\t|\s|全部班级)/g,'');
    }
    if((searchType&2)==2){
    	$instituteName=$("#ins button").text().replace(/(\\n|\\t|\s|全部学院)/g,'');
        $majorName=$("#major button").text().replace(/(\\n|\\t|\s|全部专业)/g,'');
        $gradeName=$("#grade button").text().replace(/(\\n|\\t|\s|全部年级)/g,'');
        $className=$("#class button").text().replace(/(\\n|\\t|\s|全部班级)/g,'');
        $info = $('.search_box input').val();
    }
    dataJson={
        pageNo:pageNo,
        pageSize:pageSize,
        instituteName:$instituteName,
        majorName:$majorName,
        gradeName:$gradeName,
        className:$className,
        info:$info
    }
}function setParameterOfDelete() {
    var array = [];
    $('input[name=pid]:checked').each(function (index,element) {
        array.push(parseInt($(element).val()));
    });
    if(array.length<1){
        hideMyModel();
        return alert('请至少选择一条家长记录！');
    }
    dataJson = {pids:array};
    showAlert();
}function setParameterOfQuery(pid) {
    dataJson={id:pid};
    setModel('家长信息查看',true,'hidden','关闭');
    clearParentInfo();
}function setParameterOfAdd() {
    setModel('家长添加',false,'visible','取消');
    clearParentInfo();
}function setParameterOfModify(pid) {
    dataJson={id:pid};
    setModel('家长编辑',false,'visible','取消');
    clearParentInfo();
}function setParameterOfImport() {

}function setParameterOfpwd(pid) {
    dataJson={id:pid};
    setModel('家长密码修改',false,'visible','取消');
    clearParentInfo();
}
/*-------------------------------向后台发送请求-------------------------------------*/
function getDataOfList() {//带参分页查询函数
    $.ajax({
        async:true,
        type:'POST',
        url:'/huaqiao/parent/find',
        data:dataJson,
        cache:false,
        dataType:'json',
        contentType:'application/x-www-form-urlencoded',
        beforeSend:function (xhr) { },
        success:function (data,textStatus,xhr) {
            var $list = data.list;
            var $itemCount = data.itemCount;
            setPageCode($itemCount,pageList,'pc');
            setDataOfList($list);
        },
        error:function (xhr,textStatus,errorInfo) { },
        complete:function (xhr,textStatus) { hideMyModel();}
    });
}
var timer;//定时器
function getDataOfDelete() {//删除家长信息函数
    hideAlert();
    hideMyModel();
    timer = setInterval(deleteParent,1000);
}
function deleteParent() {
    clearInterval(timer);
    $.ajax({
        type:'POST',
        url:'/huaqiao/parent/delete',
        async:true,
        cache:false,
        traditional: true,
        data:dataJson,
        dataType:'json',
        contentType:'application/x-www-form-urlencoded',
        beforeSend:function (xhr) {
        },
        success:function (data,textStatus,xhr) {
            alert("家长信息删除：失败"+data+"条！");
            pageNo=1;
            showMyModel('list');
        },
        error:function (xhr,textStatus,errorInfo) { },
        complete:function (xhr,textStatus) {
        }
    });
}
function getDataOfQuery() {//查询一条家长信息
    $.ajax({
        async:true,
        type:'POST',
        url:'/huaqiao/parent/getParent',
        data:dataJson,
        cache:false,
        dataType:'json',
        contentType:'application/x-www-form-urlencoded',
        beforeSend:function (xhr) { },
        success:function (data,textStatus,xhr) {
            setParentInfo(data);
        },
        error:function (xhr,textStatus,errorInfo) { },
        complete:function (xhr,textStatus) { }
    });
}
function editParent() {//添加、修改家长信息
    var url = '/huaqiao/parent/add';
    if(dataJson.id!=''){
        url = '/huaqiao/parent/modify';
    }
    $.ajax({
        async:true,
        type:'POST',
        url:url,
        data:dataJson,
        cache:false,
        dataType:'json',
        contentType:'application/x-www-form-urlencoded',
        beforeSend:function (xhr) {$('#myModal').modal('hide');},
        success:function (data,textStatus,xhr) {
            alert(data);
            pageNo=1;
            showMyModel('list');
        },
        error:function (xhr,textStatus,errorInfo) {
        },
        complete:function (xhr,textStatus) {
        }
    });
}
function editParentPwd() {//修改家长密码
    if(dataJson.id!=''){
        url = '/huaqiao/parent/modify';
    }
    $.ajax({
        async:true,
        type:'POST',
        url:url,
        data:dataJson,
        cache:false,
        dataType:'json',
        contentType:'application/x-www-form-urlencoded',
        beforeSend:function (xhr) {$('#myModal1').modal('hide');},
        success:function (data,textStatus,xhr) {
            alert(data);
            pageNo=1;
            showMyModel('list');
        },
        error:function (xhr,textStatus,errorInfo) {
        },
        complete:function (xhr,textStatus) {
        }
    });
}
/*-------------------------------设置页面数据-------------------------------------*/
//设置主要数据
function setDataOfList($list) {
    var str = '';
    for(var i=0;i<$list.length;i++){
        str += "<tr>";
        str += "<td><input type='checkbox' name='pid' id='parent" + i + "' value='" + $list[i].id + "'></td>";
        str += "<td>" + (Pagination.itemStart+i+1) + "</td>" +
            "<td>" + $list[i].parentName + "</td>" +
            "<td>" + $list[i].mobile + "</td>" +
            "<td>" + $list[i].address + "</td>" +
            "<td>" + $list[i].stuName + "</td>" +
            "<td>" + $list[i].relation + "</td>";
        str += "<td><a href='#' onclick=\"showMyModel('query','"+$list[i].id+"')\" >查看</a>/<a href='#' onclick=\"showMyModel('modify','"+$list[i].id+"')\">编辑</a>/<a href='#' onclick=\"showMyModel('pwd','"+$list[i].id+"')\">修改密码</a></td>";
        str += "</tr>";
    }
    $('#pageCount').text(Pagination.pageCount);
    $("#parent_tbody").html(str);
}
function setParentInfo(parent) {
    $('#pid').val(parent.id);
    $('#pName').val(parent.parentName);
    $('#pMobile').val(parent.mobile);
    $('#pAddress').val(parent.address);
    $('#pRelation').val(parent.relation);
    $('#pStuCode').val(parent.stuCode);
}
function getParentInfoPwd() {		//修改家长密码
	var pName = $('#pName').val();
    var pMobile = $('#pMobile').val();
    var pAddress = $('#pAddress').val();
    var pRelation = $('#pRelation').val();
    var pStuCode = $('#pStuCode').val();
    var pPassword = $('#pPassword').val();
    var pPassword2 = $('#pPassword2').val();
    if($('#pPassword').val() ==''){
    	return $('#information1').text("密码不能为空");
    }
    if(!(/^.{6,}$/.test(pPassword))){
        return $('#information1').text("密码不能少于六位");
    }
    if($('#pPassword').val() != $('#pPassword2').val()){
    	return $('#information1').text("两次密码输入的不一致");
    }
    dataJson={
    		parentName: pName,
    		mobile: pMobile,
    		address: pAddress,
			relation: pRelation,
			stuCode: pStuCode,
			password:pPassword,
			id:$('#pid').val(),
			code:'',
			stuName:''
    };
    editParentPwd();
}
function getParentInfo() {//setDataOfAdd
    var pName = $('#pName').val();
    var pMobile = $('#pMobile').val();
    var pAddress = $('#pAddress').val();
    var pRelation = $('#pRelation').val();
    var pStuCode = $('#pStuCode').val();
    if(pName=="" && pMobile=="" && pAddress=="" && pRelation=="" && pStuCode==""){
        return $('#information').text("请输入相关信息");
    }else if (pName=="" || pMobile=="" || pAddress=="" || pRelation=="" || pStuCode==""){
        return $('#information').text("请输入完整信息");
    }
    if(!(/^1[34578]\d{9}$/.test(pMobile))){
        return $('#information').text("请输入正确手机号码");
    }
    if(!(/^\d{10}$/.test(pStuCode))){
        return $('#information').text("学号请输入10位的纯数字");
    }
    if($('#pName').val()==''){
        return alert('姓名不能为空');
    }else if($('#pStuCode').val()==''){
        return alert('学号不能为空');
    }
    dataJson={
        parentName: pName,
        mobile: pMobile,
        address: pAddress,
        relation: pRelation,
        stuCode: pStuCode,
        id:$('#pid').val(),
        code:'',
        stuName:''
    };
    editParent();
}
function clearParentInfo() {//setDataOfAdd
    $('#pName').val('');
    $('#pMobile').val('');
    $('#pAddress').val('');
    $('#pRelation').val('');
    $('#pStuCode').val('');
    $('#information').text('');
}

function setModel(title,flag,ok,cancel){
    $('#myModalLabel').text(title);
    $('#pName').attr('disabled',flag);
    $('#pMobile').attr('disabled',flag);
    $('#pAddress').attr('disabled',flag);
    $('#pRelation').attr('disabled',flag);
    $('#pStuCode').attr('disabled',flag);
    $('#myModal .ok').css('visibility',ok);
    $('#myModal .cancel').text(cancel);
}

/*
 -----------------------------------------------------------------------------*/

//设置层次查询级联效果


var setOrg = function () {
    var url = "/huaqiao/StudentBack/getOrg?time=" + new Date().getTime();
    	$.getJSON(url, function (strJSON) {
            //绑定学院按钮
            $("#ins button").click(function () {
                $("#ins ul li").remove();
                $("#ins ul").append("<li><a href='#'>" + titleList[0] + "</a></li>");
                $("#ins ul li:last").click(function () {
                    $("#ins button").html($(this).text()+" <span class='caret'></span>");
                    $("#major button").html(titleList[1]+" <span class='caret'></span>");
                    $("#class button").html(titleList[2]+" <span class='caret'></span>");
                    pageNo = 1;
                    showMyModel('list',2);
                });
                for (var i = 0; i < strJSON.length; i++) {
                    $("#ins ul").append("<li><a href='#'>" + strJSON[i].institutename + "</a></li>");
                    $("#ins ul li:last").click(function () {
                        $("#ins button").html($(this).text()+" <span class='caret'></span>");
                        $("#major button").html(titleList[1]+" <span class='caret'></span>");
                        $("#class button").html(titleList[2]+" <span class='caret'></span>");
                        pageNo = 1;
                        showMyModel('list',2);
                        //type = 3;
                    });
                }
            });

            //绑定专业按钮
            $("#major button").click(function () {
                $("#major ul li").remove();
                $("#major ul").append("<li><a href='#'>" + titleList[1] + "</a></li>");
                $("#major ul li:last").click(function () {
                    $("#major button").html($(this).text()+" <span class='caret'></span>");
                    $("#class button").html(titleList[2]+" <span class='caret'></span>");
                    pageNo = 1;
                    showMyModel('list',2);
                });
                for (var i = 0; i < strJSON.length; i++) {
                    if (strJSON[i].institutename == $.trim($("#ins button").text())) {
                        for (var j = 0; j < strJSON[i].majorInfos.length; j++) {
                            $("#major ul").append("<li><a href='#'>" + strJSON[i].majorInfos[j].majorname + "</a></li>");
                            $("#major ul li:last").click(function () {
                                $("#major button").html($(this).text()+" <span class='caret'></span>");
                                $("#class button").html(titleList[2]+" <span class='caret'></span>");
                                pageNo = 1;
                                showMyModel('list',2);
                            });
                        }
                    }
                }
            });

            //绑定班级按钮
            $("#class button").click(function () {
            	var gradeTemp = $("#grade button").text();
                $("#class ul li").remove();
                $("#class ul").append("<li><a href='#'>" + titleList[2] + "</a></li>");
                $("#class ul li:last").click(function () {
                	$("#class button").html($(this).text()+" <span class='caret'></span>");
                    pageNo = 1;
                    showMyModel('list',2);
                });
                for (var i = 0; i < strJSON.length; i++) {
                    if (strJSON[i].institutename == $.trim($("#ins button").text())) {
                        for (var j = 0; j < strJSON[i].majorInfos.length; j++) {
                            if (strJSON[i].majorInfos[j].majorname == $.trim($("#major button").text())) {
                            	for (var k = 0; k < strJSON[i].majorInfos[j].classInfos.length; k++) {
                                    $("#class ul").append("<li><a href='#'>" + strJSON[i].majorInfos[j].classInfos[k].classname + "</a></li>");
                                    $("#class ul li:last").click(function () {
                                    	$("#class button").html($(this).text()+" <span class='caret'></span>");
                                        pageNo = 1;
                                        showMyModel('list',2);
                                    });
                                }
                            }
                        }
                    }
                }
            });
            
            
            //绑定年级按钮
            $("#grade button").click(function () {
                var grades = ["2015级","2016级","2017级","2018级","2019级","2020级","2021级","2022级","2023级","2024级","2025级"];
                $("#grade ul li").remove();
                $("#grade ul").append("<li><a href='#'>" + titleList[3] + "</a></li>");
                $("#grade ul li:last").click(function () {
                	$("#grade button").html($(this).text()+" <span class='caret'></span>");
                    pageNo = 1;
                    showMyModel('list',2);
                });
                $(grades).each(function (i) {
                    $("#grade ul").append("<li><a href='#'>" + this + "</a></li>");
                    $("#grade ul li:last").click(function () {
                    	$("#grade button").html($(this).text()+" <span class='caret'></span>");
                        pageNo = 1;
                        showMyModel('list',2);
                    });
                })
            });

            
    });
};
//重置层次选择区域
var resetOrg = function () {
    var insHtml = $("#ins button").html();
    var majorHtml = $("#major button").html();
    var gradeHtml = $("#grade button").html();
    var classHtml = $("#class button").html();
    var addModel = $("#addModel").html();

    $("#searchReset1").click(function () {
        $("#ins button").html(insHtml);
        $("#major button").html(majorHtml);
        $("#grade button").html(gradeHtml);
        $("#class button").html(classHtml);
        pageNo = 1;
        showMyModel('list',0);
    });

    $("#addCancel").click(function () {
        $("#addModel").html(addModel);
    });
    
    
    var upadteTeaPassWord=function () {
    console.log($('#possword').val());
    var possWord=$('#password').val();
    var code=$('#account').val();
    var url = "/huaqiao/teacher/updateTeaPassWord?account=" + account + "&possWord=" + Tpassword;
    $.ajax({
        async:true,
        type:'POST',
        url:url,
        cache:false,
        dataType:'json',
        contentType:'application/x-www-form-urlencoded',
        // beforeSend:function (xhr) {$('#myModal').modal('hide');},
        beforeSend:function(xhr){
        },
        success:function (data,textStatus,xhr) {
            console.log("success");
            // alert(data);
            // pageNo=1;
            // showMyModel('list');
        },
        error:function (xhr,textStatus,errorInfo) {
            console.log("error");
        },
        complete:function (xhr,textStatus) {
            console.log("complete");
        }
    });
}
};
